package com.ww.java7.filelist;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

/**
 * Java7引入了DirectoryStream文件列表流，可以进行渐进式的文件遍历，每次读取一定数量，降低遍历时性能开销
 * DirectoryStream遍历时只会遍历它的直接目录和文件，不会递归遍历子目录
 */
public class NewDemo {

    public static void main(String[] args) throws IOException {
//        test01();
        test02();
    }

    static void test01() throws IOException {
        String pathStr = "D:\\";
//        Path直接遍历方式，不会遍历子目录
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(pathStr))) {
            for (Path pathTmp : directoryStream) {
                System.out.println("DirectoryStream：" + pathTmp);
            }
        }

        // 筛选Java文件
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(pathStr), "*.java")) {
            for (Path pathTmp : directoryStream) {
                System.out.println("Java文件：" + pathTmp);
            }
        }
    }

    /**
     * Java 8对Files类进行了增强，引入了Java 8的Lambda表达式，增加了walk方法
     */
    static void test02() throws IOException {
        Stream<Path> pathStream = Files.walk(Paths.get("D:\\工作"));
        pathStream.forEach(pathTmp -> {
            System.out.println("Stream：" + pathTmp.toString());
        });

        // 筛选class文件
        pathStream = Files.walk(Paths.get("D:\\工作"));
        pathStream.filter(pathTmp -> pathTmp.toString().endsWith(".class"))
                .forEach(pathTmp -> {
                    System.out.println("class文件：" + pathTmp.toString());
                });
    }
}
